package ds.queue;

public class Queue {

	private int maxSize;
	private long[] queArray;
	private int front;
	private int rear;
	private int nItems;
	//------------------------------------------
	public Queue(int maxSize) {
		this.maxSize = maxSize;
		queArray = new long[maxSize];
		front = 0;
		rear = -1;
		nItems = 0;
	}
	
	public void insert(long value) throws Exception// put item at rear of queue
	{
		if(!isFull())
		{
			if(rear == maxSize-1) // deal wth wraparound
				rear = -1;
			queArray[++rear] = value;
			nItems++;
		}
		else
			throw new Exception("队列已满，无法插入数据");
	}
	
	public long remove() throws Exception// take item from front of queue
	{
		if(!isEmpty()){
			long value = queArray[front++]; // get valueand increase front
			if(front == maxSize) // deal with wraparound
			{
				front = 0;
			}
			nItems--;
			return value;
		}
		else
			throw new Exception("队列已空，无法移除数据");
	}
	
	public long peekFront()
	{
		return queArray[front];
	}
	
	public boolean isEmpty()
	{
		return nItems == 0;
	}
	
	public boolean isFull()
	{
		return nItems == maxSize;
	}
	
	public int size()
	{
		return nItems;
	}
	
	public void printQueue() {
		int p = front;
		for (int i=0;i<=nItems-1;i++)
		{
			System.out.print(queArray[p++ % maxSize]+" ");
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		Queue q = new Queue(5);
		q.insert(1);
		q.insert(2);
		
		q.remove();
		q.remove();
		
		q.insert(3);
		q.insert(4);
		q.insert(6);
		q.insert(6);
		q.insert(6);
		
//		while(!q.isEmpty())
//		{
//			System.out.print(q.remove()+" ");
//		}
		
		q.printQueue();
	}
}
